package com.guli.coupon.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.vo.MemberRespVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author zzb
 * @Date 2024/5/29 21:03
 * @Version 1.0
 * @description
 */
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> memberRespThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        String jsonString = JSON.toJSONString(loginUser);
        MemberRespVo memberRespVo = JSON.parseObject(jsonString, new TypeReference<MemberRespVo>() {
        });
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/coupon/**", request.getRequestURI());
        System.out.println(request.getRequestURI());
        if (match) {
            return true;
        }
        //用户未登录
        if (memberRespVo == null) {
            request.getSession().setAttribute("msg", "请先进行登录");
            response.sendRedirect("redirect:http://auth.gulimall.com/reg.html");
            return false;
        }
        //用户已登录
        memberRespThreadLocal.set(memberRespVo);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(3600);
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
